import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:fwanandroid/model/api/exceptions/ApiException.dart';
import 'package:fwanandroid/model/api/exceptions/HttpException.dart';
import 'package:fwanandroid/model/bean/ApiResponse.dart';

class ErrorInterceptor extends InterceptorsWrapper {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    ApiResponse apiResponse = ApiResponse.createApiResponse(response);
    if (apiResponse.errorCode != 0) {
      handler.reject(
          DioException(
              requestOptions: response.requestOptions,
              response: response,
              type: DioExceptionType.unknown,
              error: ApiException(
                  code: apiResponse.errorCode ?? -1,
                  message: apiResponse.errorMsg ?? 'unknow error')),
          true);
    } else {
      handler.next(response);
    }
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.error is ApiException) {
      // 业务异常，已经处理了
      super.onError(err, handler);
    } else {
      HttpException httpException = HttpException.parse(err);

      /// dio默认的错误实例，如果是没有网络，只能得到一个未知错误，无法精准的得知是否是无网络的情况
      /// 这里对于断网的情况，给一个特殊的code和msg
      // if (err.type == DioExceptionType.unknown) {
      //   var connectivityResult = await (Connectivity().checkConnectivity());
      //   if (connectivityResult == ConnectivityResult.none) {
      //     httpException = HttpException(-100, 'None Network.');
      //   }
      // }

      /// 将自定义的HttpException
      DioException newDioException = err.copyWith(error: httpException);
      super.onError(newDioException, handler);
    }
  }
}
